<script setup lang="ts">
import { getEnumSelectOptions } from '@/types/global/enums/enums_api_index'
import { PropType, onBeforeMount, ref, watch } from 'vue';
import {EnumTypeLable} from '@/types/global/enums/enums_types'

const selectedValue=defineModel();

const props = defineProps({
    /**
     * 字典类型编码(eg: 性别-gender)
     */
     enumTypeLabel: {
        type: String as PropType<EnumTypeLable>,
        required: true,
    },
    // modelValue: {
    //     type: [String, Number],
    // },
    placeholder: {
        type: String,
        default: '请选择',
    },
    disabled: {
        type: Boolean,
        default: false,
    },
})

// const emits = defineEmits(['update:modelValue']) // 父组件监听事件，同步子组件值的变化给父组件
const options = ref<TypeOptionI[]>([])

// const selectedValue = ref<string | number | undefined>()

watch([options, selectedValue], ([newOptions, newModelValue]) => {
    // 下拉数据源加载未完成不回显
    if (options.value.length === 0) {
        return
    }
    console.log('newModelValue = ', newModelValue)

    if (newModelValue == undefined) {
        selectedValue.value = undefined
        return
    }
    if (typeof newOptions[0].value === 'number') {
        selectedValue.value = Number(newModelValue)
    } else if (typeof newOptions[0].value === 'string') {
        console.log('in string if')
        selectedValue.value = String(newModelValue)
    } else {
        selectedValue.value = newModelValue
    }
})

function handleChange(val?: string | number) {
    // emits('update:modelValue', val)
}

onBeforeMount(() => {
    // 根据字典类型编码(typeCode)获取字典选项
    getEnumSelectOptions(props.enumTypeLabel).then((reponse) => {
        options.value = reponse.data
    })
})


</script>
<template>
    <el-select
        v-model="selectedValue"
        :placeholder="placeholder"
        :disabled="disabled"
        clearable
        @change="handleChange"
    >
        <el-option
            v-for="option in options"
            :key="option.value"
            :label="option.label"
            :value="option.value"
        />
    </el-select>
</template>
<style lang="scss" scoped></style>
